<template>
  <div class="dashboard_box">
    <div class="add_btn_top" style="padding-right: 20px;">
      <el-radio-group v-model="type" size="mini">
        <el-radio-button label="图表"></el-radio-button>
        <el-radio-button label="卡片"></el-radio-button>
      </el-radio-group>
      <el-divider direction="vertical"></el-divider>
      <!-- 设备筛选 -->
      <SearchDeviceChecked
        :isIndeterminate="isIndeterminate"
        :checkAll.sync="checkAll"
        :options="resultArray"
        @handleCheckAllChange="handleCheckAllChange"
        @handleCheckedDeviceChange="handleCheckedDeviceChange"
        v-model="checkList"
      ></SearchDeviceChecked>
      <el-divider direction="vertical"></el-divider>
      <!-- 站点筛选 -->
      <SearchSiteradio
        :options="uniqueSite"
        @handleCheckedSiteChange="handleCheckedSiteChange"
        v-model="checkListSite"
      ></SearchSiteradio>
    </div>
    <div v-init-screen-h="0" class="svg_box">
      <div v-if="type == options[0]" class="flex-y" v-init-screen-h="0">
        <Statistics v-if="type == options[0]"></Statistics>
        <EchartImg
          @handleClick="handleClick"
          v-if="checkListSite == ''"
          style="width: 100%;"
          :resultArray="searchList"
        ></EchartImg>
        <ChemistrySvg
          @handleClick="handleClick"
          :activeName="checkListSite"
          class="svg_item"
          v-else-if="checkListSite == '化学单元'"
          style="width: 100%;"
          ref="chemistrySvgRef"
          :resultArray="searchList2"
        ></ChemistrySvg>
        <RoutineSvg
          @handleClick="handleClick"
          :activeName="checkListSite"
          class="svg_item"
          v-else-if="checkListSite == '常规单元'"
          style="width: 100%;"
          ref="chemistrySvgRef"
          :resultArray="searchList2"
        ></RoutineSvg>
        <VacuumSvg
          @handleClick="handleClick"
          :activeName="checkListSite"
          class="svg_item"
          v-else-if="checkListSite == '真空单元'"
          style="width: 100%;"
          ref="chemistrySvgRef"
          :resultArray="searchList2"
        ></VacuumSvg>
      </div>
      <DeviceCard v-else :resultArray="searchList"></DeviceCard>
    </div>
  </div>
</template>

<script>
let timer = null;
const TYPES = ["图表", "卡片"];
import Statistics from "./components/Statistics.vue";
import EchartImg from "./components/EchartImg.vue";
import RoutineSvg from "./components/RoutineSvg.vue";
import DeviceCard from "./components/DeviceCard.vue";
import SearchDeviceChecked from "./components/SearchDeviceChecked.vue";
import SearchSiteradio from "./components/SearchSiteradio.vue";
import VacuumSvg from "./components/VacuumSvg.vue";
import { getCentralizedShops } from "@/api/centralized";
import { DEVICE_LIST } from "./constant";
import ChemistrySvg from "./components/ChemistrySvg.vue";
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import SiteTabs from "./components/SiteTabs.vue";
let client = null;
import _ from "lodash";
export default {
  components: {
    VacuumSvg,
    RoutineSvg,
    EchartImg,
    DeviceCard,
    SearchDeviceChecked,
    SearchSiteradio,
    ChemistrySvg,
    Statistics,
    SiteTabs
  },
  data() {
    return {
      activeName: "总览",
      checkListSite: "", //多选站点
      checkList: [], //多选设备
      type: TYPES[0],
      options: TYPES,
      resultArray: [], //设备列表
      uniqueSite: [], //站点列表
      isIndeterminate: false, //全选状态
      checkAll: true //全选状态
    };
  },
  computed: {
    // 筛选后的设备
    searchList2() {
      const arr = this.resultArray.filter(
        item =>
          item.manufactureSite == this.checkListSite &&
          this.checkList.includes(item.deviceToken)
      );
      return arr;
    },

    searchList() {
      return this.resultArray.filter(item =>
        this.checkList.includes(item.deviceToken)
      );
    },
    // // 获取任务保温阶段的百分比
    percentage() {
      return function(item) {
        const { programRunTime, programSetTime, programRemainTime } = item;
        const pgmSetTime = Number(programSetTime || 0);
        const pgmRemainTime = Number(programRemainTime || 0);
        const percentage = pgmSetTime - pgmRemainTime;
        const n = isNaN(percentage) ? 0 : percentage;
        return n < 0 ? 0 : n;
      };
    }
  },
  async mounted() {
    await this.init();
    this.renderMqtt();
    this.timeOut();
  },
  methods: {
    // 设置是否全选
    setAllValue() {
      let checkedCount = this.checkList.length;
      this.checkAll = checkedCount === this.resultArray.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.resultArray.length;
    },
    handleCheckedSiteChange(val) {
      if (!val) {
        this.checkList = this.resultArray.map(item => item.deviceToken);
      } else {
        // 选择站点的时候 同步修改设备的
        this.checkList = this.resultArray
          .filter(item => item.manufactureSite == val)
          .map(item => item.deviceToken);
      }
      this.setAllValue();
      this.setTextXY();
    },
    // 设备单选
    handleCheckedDeviceChange(value) {
      this.setAllValue();
      // 选择之后同步修改站点
      // const val = this.resultArray
      //   .filter(item => value.includes(item.deviceToken))
      //   .map(item => item.manufactureSite);
      // this.checkListSite = [...new Set(val)];
      // this.checkListSite = "";
    },
    // 设备全选
    handleCheckAllChange(val) {
      // this.checkListSite = "";
      // 全选的时候 同步修改站点
      // const v = this.resultArray
      //   .filter(item => this.checkList.includes(item.deviceToken))
      //   .map(item => item.manufactureSite);
      // this.checkListSite = [...new Set(v)];
      this.isIndeterminate = false;
    },
    // 算出浮窗的 xy坐标
    setTextXY() {
      setTimeout(() => {
        this.$nextTick(() => {
          this.resultArray.forEach(item => {
            if (this.$refs.chemistrySvgRef) {
              const path = this.$refs.chemistrySvgRef.$refs[
                `path${item.deviceToken}`
              ];
              if (path) {
                const xy = path[0].getBBox();
                this.$set(item, "d0x", xy.x + 22);
                this.$set(item, "d0y", xy.y - 10);
              }
            }
          });
        });
      }, 2000);
    },
    //定时器
    timeOut() {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
      timer = setInterval(async () => {
        this.initTime();
      }, 5000);
      this.$once("hook:beforeDestroy", () => {
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
      });
    },
    handleClick(data) {
      this.$router.push({
        name: "deviceOperation",
        params: {
          token: data.token,
          deviceRow: JSON.stringify({
            ...data
            // deviceToken: "1307033",
          })
        }
      });
    },
    // 轮询
    async initTime() {
      return new Promise(async (resolve, rejcet) => {
        const res = await getCentralizedShops();
        const { results } = res.data;
        const map = new Map();
        results.forEach(ele => {
          map.set(ele.deviceToken, ele);
        });

        this.resultArray.forEach(item => {
          if (map.has(item.deviceToken)) {
            // 更新必要信息
            item.taskDownLoadInfo = map.get(item.deviceToken).taskDownLoadInfo;
            item.programRemainTime = map.get(
              item.deviceToken
            ).programRemainTime;
            item.programSetTime = map.get(item.deviceToken).programSetTime;
            item.programRunTime = map.get(item.deviceToken).programRunTime;
            item.deviceStatus = map.get(item.deviceToken).deviceStatus;
            this.$set(item, "config", {
              value: this.percentage(map.get(item.deviceToken)),
              // value: 80,
              borderWidth: 1.5,
              localGradient: true,
              lineDash: [3, 2]
            });
          }
        });
        resolve();
      });
    },
    async init() {
      return new Promise(async (resolve, rejcet) => {
        //  this.getCentralizedStats();
        const res = await getCentralizedShops();
        const { results } = res.data;
        // 获取站点
        this.uniqueSite = [
          ...new Set(
            results
              .map(obj => {
                return obj.manufactureSite;
              })
              .filter(item => item)
          )
        ];
        this.checkList = results.map(item => item.deviceToken);
        // this.checkListSite = this.uniqueSite.map(item => item);
        const map = new Map();
        DEVICE_LIST.forEach(ele => {
          map.set(ele.deviceToken, ele);
        });

        results.forEach(item => {
          this.$set(item, "meter1RunStageNO", 0);
          this.$set(item, "config", {
            value: this.percentage(item),
            // value: 80,
            borderWidth: 1.5,
            localGradient: true,
            lineDash: [3, 2]
          });
          if (map.has(item.deviceToken)) {
            item.x = map.get(item.deviceToken).x;
            item.y = map.get(item.deviceToken).y;
            item.d1 = map.get(item.deviceToken).d1;
            item.d2 = map.get(item.deviceToken).d2;
            item.d3 = map.get(item.deviceToken).d3;
          }
        });
        // const w = results.filter(item => item.deviceToken == 1344118);
        this.resultArray = results;
        this.setTextXY();
        resolve();
      });
    },
    renderMqtt() {
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + "/mqtt"
      };
      let flg = false;
      this.resultArray.forEach(item => {
        const tenantToken = this.$store.state.user.tenant.token;
        // 13020086
        const tenantTopic = `$avic/superlink/iot/${tenantToken}/${item.deviceToken}/measurement`;
        const initmqtt = new initMqtt(param);
        client = initmqtt.connect(() => {
          // console.log("mqtt连接成功,开始订阅主题", tenantTopic);
          client.subscribe(tenantTopic);
        });
      });
      const messageHandler = (topic, message) => {
        var obj = JSON.parse(message.toString());
        const { request, deviceToken } = obj;
        const { metadata } = request;
        const {
          meter1RealTemp,
          meter3RealTemp,
          meter2RealTemp,
          meter1RunStageNO
        } = metadata;
        this.resultArray.forEach(item => {
          if (item.deviceToken == deviceToken) {
            item.firstRealTemp = meter1RealTemp;
            item.secondRealTemp = meter2RealTemp;
            item.thirdRealTemp = meter3RealTemp;
            this.$set(
              item,
              "meter1RunStageNO",
              !meter1RunStageNO ? 0 : Number(meter1RunStageNO)
            );
          }
        });
        // if (!flg) {
        //   console.log("mqtt :>> ", obj);
        // }
        // flg = true;
      };
      client.on("message", (topic, message) => {
        messageHandler(topic, message);
      });
    }
  },
  beforeDestroy() {
    console.log("销毁mqtt: ", client);

    if (client) {
      client.end(true);

      client = null;
    }
  }
};
</script>

<style scoped lang="scss">
.svg_box {
  overflow: hidden !important;
  .svg_item {
    overflow: hidden !important;
  }
}
.dashboard_box {
  position: relative;
  color: #fff;
  background: url(../../../assets/images/applicationCenter/app_bg.jpg) no-repeat
    100%;
  background-size: cover;
  width: 100%;
  height: 100%;
}
</style>
